# -*- coding: utf-8 -*-
# @Time   : 2022-06-06 17:51:04
# @Author : 搬砖客

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import ddddocr
from utils.logging_utils.log_util import write_log, write_error_log
from utils.process_files_utils.yaml_util import YamlUtil


class GetToken:
    driver = None
    url = YamlUtil().read_config_yaml("url", "url_imotor")
    print(url)
    ocr = ddddocr.DdddOcr()
    dingtalk_url = "https://oapi.dingtalk.com/robot/send?access_token=4xxxxxxxxxxx"

    @classmethod
    def get_driver(cls):
        if cls.driver is None:
            try:
                chrome_options = webdriver.ChromeOptions()
                chrome_options.add_argument('--headless')
                chrome_options.add_argument('--no-sandbox')
                chrome_options.add_argument('--disable-gpu')
                chrome_options.add_argument('--disable-dev-shm-usage')
                chrome_options.add_argument('--start-maximized')
                cls.driver = webdriver.Chrome(options=chrome_options)
                cls.driver.maximize_window()
                cls.driver.get(cls.url)
                # cls.driver.save_screenshot("all.png")
            except Exception as e:
                write_error_log(f"创建driver，打开网页失败,错误信息为：{e}")
        return cls.driver

    def get_code_image(self, filename="ocr_img.png"):
        driver = GetToken.get_driver()
        time.sleep(3)
        # 搜索结果部分完整截图
        r_node = driver.find_element(by='xpath', value="//div[@class='captchaImg___3cpyl']//img")
        r_node.screenshot(filename)
        time.sleep(1)
        return filename

    def get_code_value(self):

        with open(self.get_code_image(), 'rb') as f:
            img_bytes = f.read()
        res = self.ocr.classification(img_bytes)
        return res

    def get_token(self):
        write_log("进行登录操作，获得token值")
        driver = GetToken.get_driver()
        username = YamlUtil().read_config_yaml("api_info", "username")
        password = YamlUtil().read_config_yaml("api_info", "password_selenium")
        write_log("获得账号密码成功")
        while True:
            try:
                code_value = self.get_code_value()
                first_num = code_value[0]
                second_num = code_value[1]
                third_num = code_value[2]
                write_log(f"识别验证码结果为：{code_value}")
                if first_num == "o":
                    first_num = 0
                if first_num == "q":
                    first_num = 9
                if second_num == "t":
                    second_num = "+"
                if second_num == "(":
                    second_num = "/"
                if third_num == "o":
                    third_num = 0
                if third_num == "q":
                    third_num = 9
                first_num = int(first_num)
                third_num = int(third_num)
                if second_num == "+":
                    code_end = first_num + third_num
                elif second_num == "-":
                    code_end = first_num - third_num
                elif second_num == "/":
                    code_end = first_num / third_num
                else:
                    code_end = first_num * third_num
                time.sleep(5)
                driver.find_element_by_css_selector("#username").clear()
                driver.find_element_by_css_selector("#username").send_keys(username)

                driver.find_element_by_css_selector("#password").clear()
                driver.find_element_by_css_selector("#password").send_keys(password)

                driver.find_element_by_css_selector("#code").clear()
                driver.find_element_by_css_selector("#code").send_keys(code_end)

                driver.find_element_by_css_selector("button[type='button']").click()
                write_log("进行登录操作和登录断言")
                check_button = WebDriverWait(driver, 10, 0.5).until(
                    EC.presence_of_element_located((By.XPATH, "//span[contains(text(),'首页')]")))
                check_button.click()
                write_log("登录成功")

                login_token = driver.execute_script('return localStorage.getItem("token")')
                # driver.quit()
                write_log(f"获取token成功，值为：{login_token}")
                driver.close()
                driver.quit()
                return login_token

            except Exception as e:
                driver.refresh()
                time.sleep(3)
                write_log(f"识别验证码失败，再次尝试，错误信息为：{e}")
